import GCBlock from "../../components/common-components/GCBlock";
import GCToast from "../../components/common-components/GCToast";
import GameLogic from "../../GameLogic";
import { GCAnalytics } from "../../GCAnalytics";
import GCConnection, { GameMode } from "../../GCConnection";
import { GameState } from "./GameState";

export class TimeLimitedState extends GameState {
    mode: GameMode = GameMode.TIMELIMITED;
    private _isOver = false;

    async enter(logic: GameLogic): Promise<void> {
        await super.enter(logic);

        this._isOver = false;
        logic.timeLimited.node.active = true;
    }

    exit(logic: GameLogic): void {
        super.exit(logic);
        logic.timeLimited.stopClock();
        logic.timeLimited.node.active = false;
    }

    async process(logic: GameLogic, type: string, answer?: any): Promise<void> {
        super.process(logic, type, answer);

        if (type == 'answer') {
            logic.timeLimited.stopClock();
        }

        if (type === 'game-over') {
            this.gameOver(logic);
        }
    }


    protected async gameOver(logic: GameLogic): Promise<void> {
        console.log(`gameOver: ${this._isOver}`);

        if (this._isOver) {
            return;
        }
        this._isOver = true;

        await super.gameOver(logic);
    }


    protected async getNextQuestion(logic: GameLogic): Promise<void> {
        GCBlock.block();
        try {

            const resp = await GCConnection.requestQuestion(null);
            this.questionList.push(resp);
            logic.classicComp.initUI(resp.pic, resp.options);

            logic.timeLimited.startClock(resp.countdown, resp.total);

        } catch (e) {
            cc.error(e);

            GCToast.toast(e.message);
            GCAnalytics.onFailed(e.message);

            logic.sm.to('menu');
            return;
        } finally {
            GCBlock.unblock();
        }
    }
}
